﻿using AlipayPay.Infrastructure.Config.ExceptionConfig;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;

namespace AlipayPay.Infrastructure.ExceptionExtensions
{
    public class GlobalExceptionFilter : IExceptionFilter
    {
        public GlobalExceptionFilter()
        {

        }

        public void OnException(ExceptionContext context)
        {
            var errorResponse = new JsonErrorResponse();

            var businessException = context.Exception as BusinessException;

            //这里面是自定义的操作记录日志
            if (businessException.Code == 401)
            {
                errorResponse.Message = context.Exception.Message;
                errorResponse.Code = businessException.Code;
                context.Result = new UnauthorizedObjectResult(errorResponse);
            }else if (context.Exception.GetType() == typeof(BusinessException))
            {
                errorResponse.Message = context.Exception.Message;
                errorResponse.Code = 400;
                context.Result = new BadRequestObjectResult(errorResponse);//返回异常数据
            }
            else
            {
                errorResponse.Code = 500;
                errorResponse.Message = "系统繁忙，请稍后重试";
                //Utils.GetLogService().LogError($"系统繁忙，请稍后重试：{errorResponse.Message}");
                context.Result = new InternalServerErrorObjectResult(errorResponse);
            }


        }
    }

    /// <summary>
    /// 内部异常结果
    /// </summary>
    public class InternalServerErrorObjectResult : ObjectResult
    {
        public InternalServerErrorObjectResult(object value) : base(value)
        {
            StatusCode = StatusCodes.Status500InternalServerError;
        }
    }
}
